package com.kyz.speechsdk.ifly;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIEvent;
import com.iflytek.aiui.AIUIListener;
import com.iflytek.aiui.AIUIMessage;
import com.kyz.speechsdk.ifly.interfaces.IAIUIListener;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * create by ZhongZihao on 2019/6/10
 */
public class AIUIManager {
    private final String TAG = "AIUIManager";
    private static AIUIManager instance;
    private AIUIAgent mAIUIAgent = null;
    private int mAIUIState = 1;
    private Context mContext;
    private IAIUIListener mmListener;
    private AIUIListener mAIUIListener = new AIUIListener() {
        public void onEvent(AIUIEvent event) {
            Log.i("AIUIManager", "on event: " + event.eventType);
            switch(event.eventType) {
                case 1:
                    try {
                        JSONObject bizParamJson = new JSONObject(event.info);
                        JSONObject data = bizParamJson.getJSONArray("data").getJSONObject(0);
                        JSONObject params = data.getJSONObject("params");
                        JSONObject content = data.getJSONArray("content").getJSONObject(0);
                        if (content.has("cnt_id")) {
                            String cnt_id = content.getString("cnt_id");
                            String cntStr = new String(event.data.getByteArray(cnt_id), "utf-8");
                            if (TextUtils.isEmpty(cntStr)) {
                                return;
                            }

                            JSONObject cntJson = new JSONObject(cntStr);
                            String sub = params.optString("sub");
                            if ("nlp".equals(sub)) {
                                String resultStr = cntJson.optString("intent");
                                if (AIUIManager.this.mmListener != null) {
                                    AIUIManager.this.mmListener.onResult(resultStr);
                                }

                                Log.i("AIUIManager", resultStr);
                            }
                        }
                    } catch (Throwable var11) {
                        var11.printStackTrace();
                        Log.i("AIUIManager", "Throwable错误: " + var11.getLocalizedMessage());
                    }
                    break;
                case 2:
                    Log.i("AIUIManager", "错误: " + event.arg1 + "\n" + event.info);
                    break;
                case 3:
                    AIUIManager.this.mAIUIState = event.arg1;
                    if (1 == AIUIManager.this.mAIUIState) {
                        Log.i("AIUIManager", "闲置状态，AIUI未开启");
                    } else if (2 == AIUIManager.this.mAIUIState) {
                        Log.i("AIUIManager", "STATE_READY");
                    } else if (3 == AIUIManager.this.mAIUIState) {
                        Log.i("AIUIManager", "STATE_WORKING");
                    }
                    break;
                case 13:
                    Log.i("AIUIManager", "已连接服务器");
                    break;
                case 14:
                    Log.i("AIUIManager", "与服务器断连");
            }

        }
    };

    private AIUIManager(Context context) {
        this.mContext = context;
        this.createAgent();
    }

    public static AIUIManager createInstance(Context cm) {
        if (instance == null) {
            instance = new AIUIManager(cm);
        }

        return instance;
    }

    public static AIUIManager getInstance() {
        return instance;
    }

    private String getAIUIParams() {
        String params = "";
        AssetManager assetManager = this.mContext.getResources().getAssets();

        try {
            InputStream ins = assetManager.open("cfg/aiui_phone.cfg");
            byte[] buffer = new byte[ins.available()];
            ins.read(buffer);
            ins.close();
            params = new String(buffer);
            JSONObject paramsJson = new JSONObject(params);
            params = paramsJson.toString();
        } catch (IOException var6) {
            var6.printStackTrace();
        } catch (JSONException var7) {
            var7.printStackTrace();
        }

        return params;
    }

    private void createAgent() {
        if (this.mAIUIAgent == null) {
            Log.i("AIUIManager", "create aiui agent");
            this.mAIUIAgent = AIUIAgent.createAgent(this.mContext, this.getAIUIParams(), this.mAIUIListener);
        }

        if (this.mAIUIAgent == null) {
            String strErrorTip = "创建AIUIAgent失败！";
            Log.v("AIUIManager", "创建AIUIAgent失败！");
        } else {
            Log.v("AIUIManager", "AIUIAgent已创建");
        }

    }

    public void destroyAgent() {
        if (this.mAIUIAgent != null) {
            Log.i("AIUIManager", "destroy aiui agent");
            this.mAIUIAgent.destroy();
            this.mAIUIAgent = null;
            instance = null;
            Log.v("AIUIManager", "AIUIAgent已销毁");
        } else {
            Log.v("AIUIManager", "AIUIAgent为空");
        }

    }

    public void startTextNlp(String text, IAIUIListener listener) {
        if (this.mAIUIAgent == null) {
            Log.v("AIUIManager", "AIUIAgent 为空，请先创建");
        } else {
            AIUIMessage wakeupMsg = new AIUIMessage(7, 0, 0, "", (byte[])null);
            this.mAIUIAgent.sendMessage(wakeupMsg);
            Log.i("AIUIManager", "start text nlp");
            this.mmListener = listener;

            try {
                String params = "data_type=text,tag=text-tag";
                byte[] textData = text.getBytes("utf-8");
                AIUIMessage write = new AIUIMessage(2, 0, 0, params, textData);
                this.mAIUIAgent.sendMessage(write);
            } catch (UnsupportedEncodingException var6) {
                var6.printStackTrace();
            }

        }
    }
}
